package sshTool

import (
	"aflow/database"
	"aflow/models"
	"golang.org/x/crypto/ssh"
	"log"
	"strconv"
)

type sshConfig struct {
	Hostname string
	Host     string
	Port     int
	Username string
	Password string
	Timeout  int
}

type ClientPool struct {
	clients map[string]*ssh.Client
}

func GetSessionFormSessionPool(pool ClientPool, hostname string) *ssh.Client {
	if session, ok := pool.clients[hostname]; ok {
		return session
	}
	return nil
}

// NewSSHPool 创建一个新的SSH连接池
func NewSSHPool() ClientPool {

	var sessionPool ClientPool
	var clients = make(map[string]*ssh.Client)

	var hosts []models.Host
	database.DB.Find(&hosts)
	for _, host := range hosts {
		var client = getClient(host.Host, host.Port, host.Username, host.Password)
		clients[host.Hostname] = client
	}
	sessionPool.clients = clients

	return sessionPool
}

func getClient(host string, port uint, username string, password string) *ssh.Client {
	config := &ssh.ClientConfig{
		User: username, // 替换为你的用户名
		Auth: []ssh.AuthMethod{
			ssh.Password(password), // 替换为你的密码
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(), // 忽略主机密钥验证(不安全，仅用于测试)
	}
	client, err := ssh.Dial("tcp", host+":"+strconv.Itoa(int(port)), config) // 替换为你的主机名或IP
	if err != nil {
		log.Fatal("连接失败: ", err)
	}
	return client
}
